package com.sooth.system.role.service;

import cn.hutool.core.collection.CollUtil;
import com.dream.template.mapper.TemplateMapper;
import com.sooth.system.role.mapper.SysRoleMenuMapper;
import com.sooth.system.role.table.SysRoleMenu;
import com.sooth.system.role.view.SysRoleMenuDto;
import com.sooth.system.role.view.SysRoleMenuVo;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@RequiredArgsConstructor
@Service
public class SysRoleMenuServiceImpl implements ISysRoleMenuService {
    private final TemplateMapper templateMapper;
    private final SysRoleMenuMapper roleMenuMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(SysRoleMenuVo roleMenuVo) {
        Long roleId = roleMenuVo.getRoleId();
        roleMenuMapper.deleteByRoleId(roleId);
        List<Long> menuIds = roleMenuVo.getMenuIds();
        if (CollUtil.isNotEmpty(menuIds)) {
            List<SysRoleMenu> roleMenus = new ArrayList<>(menuIds.size());
            for (Long menuId : menuIds) {
                roleMenus.add(new SysRoleMenu(roleId, menuId));
            }
            templateMapper.batchInsert(roleMenus);
        }
    }

    @Override
    public List<SysRoleMenu> list(SysRoleMenuDto roleMenu) {
        return templateMapper.selectList(SysRoleMenu.class, roleMenu);
    }
}
